<?php
//留言板
//全局时间
date_default_timezone_set('Asia/Shanghai');

//数据库连接
$link = mysql_connect("localhost","abc","");
if (!$link) {
    die('无法连接数据库: ' . mysql_error());
}

mysql_query('set names utf8');
mysql_select_db("test");

//提交留言
if (isset($_POST['submitted'])) {
	$content 	= !empty($_POST['content']) ? clean($_POST['content']) : '';
	$name 		= !empty($_POST['name']) ? clean($_POST['name']) : '';
	
	if (!empty($content) && !empty($name)) {
		//插入留言
		$sql = "INSERT INTO msg(`content`, `name`) VALUES('$content', '$name')";
		mysql_query($sql);
	}
}

//查找所有留言内容
$sql = "SELECT * FROM msg ORDER BY add_time DESC";
$result = mysql_query($sql);

$list = array();
if (!empty($result)) {
	while ($row = mysql_fetch_assoc($result)) {
		$list[] = $row;
	}
}

//输入字符过滤 转义引号
function clean($data) 
{
	if (!empty($data) && is_string($data)) {
		$data = mysql_real_escape_string($data);
	}
	return $data;
}
?>
<html>
<head>
	<title>留言板</title>
</head>
<body>
	<h1>留言板</h1>
	<table>
		<tr>
			<th width="10%">ID</th>
			<th width="60%">内容</th>
			<th width="10%">姓名</th>
			<th width="20%">时间</th>
		</tr>
		<?php if (!empty($list)):?>
			<?php foreach ($list as $value):?>
			<tr>
				<td align="middle"><?php echo $value['id'];?></td>
				<td align="middle"><?php echo $value['content'];?></td>
				<td align="middle"><?php echo $value['name'];?></td>
				<td align="middle"><?php echo $value['add_time'];?></td>
			</tr>
			<?php endforeach;?>
		<?php endif;?>
	</table>
	
	<br />
	<form method="post" action="">
		内容：<textarea name="content" cols="40" rows="10"></textarea><br />
		姓名：<input type="text" name="name" value="" /><br />
		<input type="submit" name="submitted" value="提交" />
	</form>
</body>
</html>
